#include <QInputDialog>
#include <QMessageBox>
#include <QGraphicsDropShadowEffect>
#include "wordpage.h"
#include "ui_wordpage.h"
#include "util/serverhelper.h"
#include "util/messagebox.h"

namespace WordMemory
{
    WordPage::WordPage(QWidget *parent)
        : QWidget(parent)
        , ui(new Ui::WordPage)
        , serverhelper(new ServerHelper(this))
    {
        ui->setupUi(this);
        setupStyles();
        setupConnections();
        loadDefaultVocabularyWords();
    }

    WordPage::~WordPage()
    {
        delete ui;
    }

    void WordPage::setupStyles()
    {
        // 样式定义：查看所有按钮
        QString viewButtonStyle = R"(
            QPushButton {
              font-family: "Microsoft YaHei";
              font-size: 12px;
              padding: 5px 10px;
              color: #ffffff;
              border-radius: 5px;
              border: none;
            }
            QPushButton:pressed {
              background-color: #096dd9;
            };)";

        ui->viewAllExamplesButton->setStyleSheet(viewButtonStyle);
        ui->viewAllMnemonicsButton->setStyleSheet(viewButtonStyle);

        // 样式定义：学习状态按钮
        QString forgotButtonStyle = R"(
            QPushButton {
              font-family: "Microsoft YaHei";
              font-size: 14px;
              padding: 8px 16px;
              background-color: #ff4d4f;
              color: #ffffff;
              border-radius: 5px;
              border: none;
            }
            QPushButton:hover {
              background-color: #ff7875;
            }
            QPushButton:pressed {
              background-color: #d4380d;
            };)";

        QString vagueButtonStyle = R"(
            QPushButton {
              font-family: "Microsoft YaHei";
              font-size: 14px;
              padding: 8px 16px;
              background-color: #faad14;
              color: #ffffff;
              border-radius: 5px;
              border: none;
            }
            QPushButton:hover {
              background-color: #ffc107;
            }
            QPushButton:pressed {
              background-color: #d48806;
            };)";

        QString knownButtonStyle = R"(
            QPushButton {
              font-family: "Microsoft YaHei";
              font-size: 14px;
              padding: 8px 16px;
              background-color: #52c41a;
              color: #ffffff;
              border-radius: 5px;
              border: none;
            }
            QPushButton:hover {
              background-color: #73d13d;
            }
            QPushButton:pressed {
              background-color: #389e0d;
            };)";

        ui->forgotButton->setStyleSheet(forgotButtonStyle);
        ui->vagueButton->setStyleSheet(vagueButtonStyle);
        ui->knownButton->setStyleSheet(knownButtonStyle);

        // 样式定义：收藏按钮
        QString favoriteButtonStyle = R"(
            QPushButton {
                font-family: "Microsoft YaHei";
                font-size: 14px;
                padding: 8px 12px;
                color: #595959;
                background-color: #f0f0f0;
                border: 1px solid #d9d9d9;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #e6e6e6;
                border-color: #bfbfbf;
            }
            QPushButton:checked {
                background-color: #fffbe6;
                color: #faad14;
                border-color: #ffe58f;
            }
            QPushButton:pressed {
                background-color: #d9d9d9;
            })";
        ui->favoriteButton->setStyleSheet(favoriteButtonStyle);
        ui->favoriteButton->setCheckable(true);


        ui->wordLabel->setStyleSheet("font-family: 'Times New Roman'; font-size: 30px;");
        ui->example1Label->setStyleSheet("font-family: 'Times New Roman'; font-size: 20px;");
        ui->example2Label->setStyleSheet("font-family: 'Times New Roman'; font-size: 20px;");
        ui->example3Label->setStyleSheet("font-family: 'Times New Roman'; font-size: 20px;");

        // 为卡片容器添加阴影效果
        QGraphicsDropShadowEffect *wordShadow = new QGraphicsDropShadowEffect(this);
        wordShadow->setBlurRadius(12);
        wordShadow->setXOffset(0);
        wordShadow->setYOffset(4);
        wordShadow->setColor(QColor(0, 0, 0, 0.1 * 255));
        ui->wordCardWidget->setGraphicsEffect(wordShadow);

        QGraphicsDropShadowEffect *examplesShadow = new QGraphicsDropShadowEffect(this);
        examplesShadow->setBlurRadius(12);
        examplesShadow->setXOffset(0);
        examplesShadow->setYOffset(4);
        examplesShadow->setColor(QColor(0, 0, 0, 0.1 * 255));
        ui->examplesCardWidget->setGraphicsEffect(examplesShadow);

        QGraphicsDropShadowEffect *mnemonicShadow = new QGraphicsDropShadowEffect(this);
        mnemonicShadow->setBlurRadius(12);
        mnemonicShadow->setXOffset(0);
        mnemonicShadow->setYOffset(4);
        mnemonicShadow->setColor(QColor(0, 0, 0, 0.1 * 255));
        ui->mnemonicCardWidget->setGraphicsEffect(mnemonicShadow);
    }

    void WordPage::setupConnections()
    {
        connect(serverhelper, &ServerHelper::getWordsByVocabularyIdFinished, this,
                [this](bool success, int vocabularyId, const QList<Word> &words, const QString &error) {
                    if (success && vocabularyId == defaultVocabulary.id) {
                        defaultWordQueue.clear();
                        for (const Word &word : words) {
                            defaultWordQueue.enqueue(word); // 加载到默认队列
                        }

                        vagueWordQueue.clear();
                        forgotWordQueue.clear();

                        if (defaultWordQueue.isEmpty()) {
                            MessageBox::info(this, "当前词库为空");
                        } else {
                            on_nextWord(); // 显示第一个单词
                        }
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "获取词库单词失败" : error);
                    }
                });

        connect(serverhelper, &ServerHelper::getWordFinished, this,
                [this](bool success, const Word &word, const QString &error) {
                    if (success) {
                        currentWord = word;
                        updateWordDisplay(currentWord);
                    } else {
                        MessageBox::warning(this, error);
                    }
                });

        connect(serverhelper, &ServerHelper::getDefaultVocabularyFinished, this,
                [this](bool success, const Vocabulary &vocabulary, const QString &error) {
                    if (success) {

                        defaultVocabulary = vocabulary;
                        serverhelper->getWordsByVocabularyId(
                                    UserManager::instance().getUserId(),
                                    defaultVocabulary.id); // 请求获取默认词库的单词

                        if (defaultVocabulary.id <= 0) {
                            MessageBox::info(this, "未设置默认词库");
                            defaultWordQueue.clear();
                            vagueWordQueue.clear();
                            forgotWordQueue.clear();
                            return;
                        }
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "获取默认词库失败" : error);
                    }
                });

        connect(serverhelper, &ServerHelper::addCustomExampleFinished, this,
                [this](bool success, const QString &error) {
                    if (success) {
                        MessageBox::info(this, "例句已添加");
                        displayWord(ui->wordLabel->text());
                    } else {
                        MessageBox::warning(this, error);
                    }
                });

        connect(serverhelper, &ServerHelper::addCustomMnemonicFinished, this,
                [this](bool success, const QString &error) {
                    if (success) {
                        MessageBox::info(this, "助记已添加");
                        displayWord(ui->wordLabel->text());
                    } else {
                        MessageBox::warning(this, error);
                    }
                });

        connect(serverhelper, &ServerHelper::updateWordStatusFinished, this,
                [this](bool success, const QString &error) {
                    if (success) {
                        // MessageBox::info(this, "学习状态已更新");
                    } else {
                        MessageBox::warning(this, error);
                    }
                });

        connect(serverhelper, &ServerHelper::addWordToFavoritesFinished, this,
                [this](bool success, int wordId, const QString &error) {
                    if (wordId != currentWord.id) return;

                    if (success) {
                        MessageBox::info(this, "单词已收藏");
                        currentWord.isFavorite = true;
                        updateFavoriteButtonState(true);
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "收藏失败" : error);
                        updateFavoriteButtonState(false);
                    }
                });
        connect(serverhelper, &ServerHelper::removeWordFromFavoritesFinished, this,
                [this](bool success, int wordId, const QString &error) {
                    if (wordId != currentWord.id) return;

                    if (success) {
                        MessageBox::info(this, "已取消收藏");
                        currentWord.isFavorite = false;
                        updateFavoriteButtonState(false);
                    } else {
                        MessageBox::error(this, error.isEmpty() ? "取消收藏失败" : error);
                        updateFavoriteButtonState(true);
                    }
                });
    }

    void WordPage::updateFavoriteButtonState(bool isFavorite)
    {
        ui->favoriteButton->setChecked(isFavorite);
        if (isFavorite) {
            ui->favoriteButton->setText("已收藏");
        } else {
            ui->favoriteButton->setText("收藏");
        }
    }

    void WordPage::on_favoriteButton_clicked()
    {
        if (!UserManager::instance().isLoggedIn() || currentWord.id == 0) {
            MessageBox::warning(this, "请先登录并选择一个单词");
            return;
        }

        if (currentWord.isFavorite) {
            serverhelper->removeWordFromFavorites(UserManager::instance().getUserId(), currentWord.id);
        } else {
            serverhelper->addWordToFavorites(UserManager::instance().getUserId(), currentWord.id);
        }
    }

    void WordPage::loadDefaultVocabularyWords()
    {
        if (!UserManager::instance().isLoggedIn()) {
            MessageBox::warning(this, "请先登录");
            return;
        }

        serverhelper->getDefaultVocabulary(UserManager::instance().getUserId());
    }

    void WordPage::displayWord(const QString &word)
    {
        if (!UserManager::instance().isLoggedIn()) {
            MessageBox::warning(this, "请先登录");
            return;
        }

        int userId = UserManager::instance().getUserId();
        serverhelper->getWord(userId, word);
    }

    void WordPage::displayCurrentWord()
    {
        ui->wordLabel->setProperty("word_id", currentWord.id);
        updateWordDisplay(currentWord);
    }

    void WordPage::updateWordDisplay(const Word &word)
    {
        ui->wordLabel->setText(word.word);
        ui->meaningLabel->setText(word.meaning);
        ui->mnemonicLabel->setText(word.mnemonics.isEmpty() ? "暂无助记" : word.mnemonics[0]);

        ui->example1Label->setText(word.examples.size() > 0 ? word.examples[0].example : "暂无例句");
        ui->example1TranslationLabel->setText(word.examples.size() > 0 ? word.examples[0].translation : "");
        ui->example2Label->setText(word.examples.size() > 1 ? word.examples[1].example : "暂无例句");
        ui->example2TranslationLabel->setText(word.examples.size() > 1 ? word.examples[1].translation : "");
        ui->example3Label->setText(word.examples.size() > 2 ? word.examples[2].example : "暂无例句");
        ui->example3TranslationLabel->setText(word.examples.size() > 2 ? word.examples[2].translation : "");

        updateFavoriteButtonState(word.isFavorite);
    }

    void WordPage::on_viewAllExamplesButton_clicked()
    {
        bool ok;
        QString example = QInputDialog::getText(this, "添加例句", "请输入例句：", QLineEdit::Normal, "", &ok);
        if (ok && !example.isEmpty()) {
            QString translation = QInputDialog::getText(this, "添加例句翻译", "请输入翻译：", QLineEdit::Normal, "", &ok);
            if (ok && !translation.isEmpty()) {
                serverhelper->addCustomExample(currentWord.id, example, translation);
            }
        }
    }

    void WordPage::on_viewAllMnemonicsButton_clicked()
    {
        bool ok;
        QString mnemonic = QInputDialog::getMultiLineText(this, "添加助记", "请输入助记：", "", &ok);
        if (ok && !mnemonic.isEmpty()) {
            serverhelper->addCustomMnemonic(currentWord.id, mnemonic);
        }
    }

    void WordPage::on_forgotButton_clicked()
    {
        if (currentQueueType == CurrentQueue::None || currentWord.id == 0) {
            MessageBox::warning(this, "无单词可操作");
            return;
        }

        forgotWordQueue.enqueue(currentWord);
        on_nextWord();
        serverhelper->updateWordStatus(UserManager::instance().getUserId(), currentWord.id, "forgot");
    }

    void WordPage::on_vagueButton_clicked()
    {
        if (currentQueueType == CurrentQueue::None || currentWord.id == 0) {
            MessageBox::warning(this, "无单词可操作");
            return;
        }

        vagueWordQueue.enqueue(currentWord);
        on_nextWord();
        serverhelper->updateWordStatus(UserManager::instance().getUserId(), currentWord.id, "vague");
    }

    void WordPage::on_knownButton_clicked()
    {
        qDebug() << "ffff";
        if (currentQueueType == CurrentQueue::None || currentWord.id == 0) {
            MessageBox::warning(this, "无单词可操作");
            return;
        }

        on_nextWord();
        serverhelper->updateWordStatus(UserManager::instance().getUserId(), currentWord.id, "known");
    }

    void WordPage::on_nextWord()
    {
        if (defaultWordQueue.isEmpty() && vagueWordQueue.isEmpty() && forgotWordQueue.isEmpty()) {

            MessageBox::info(this, "当前词库已背诵完毕");
            QString buttonDisableStyle = R"(
                QPushButton { font-family: "Microsoft YaHei"; font-size: 14px; padding: 8px 16px; background-color: #ff4d4f; color: #ffffff; border-radius: 5px; border: none; }
                QPushButton:hover { background-color: #ff7875; }
                QPushButton:pressed { background-color: #d4380d; }
                QPushButton:disabled { background-color: #cccccc; color: #666666; })";

            ui->forgotButton->setStyleSheet(buttonDisableStyle);
            ui->vagueButton->setStyleSheet(buttonDisableStyle);
            ui->knownButton->setStyleSheet(buttonDisableStyle);

            ui->forgotButton->setEnabled(false);
            ui->vagueButton->setEnabled(false);
            ui->knownButton->setEnabled(false);
            ui->forgotButton->setText("完毕");
            ui->vagueButton->setText("完毕");
            ui->knownButton->setText("完毕");
            return;
        }

        if (!vagueWordQueue.isEmpty()) {
            currentWord = vagueWordQueue.dequeue();
            currentQueueType = CurrentQueue::Vague;
        } else if (!defaultWordQueue.isEmpty()) {
            currentWord = defaultWordQueue.dequeue();
            currentQueueType = CurrentQueue::Default;
        } else if (!forgotWordQueue.isEmpty()) {
            currentWord = forgotWordQueue.dequeue();
            currentQueueType = CurrentQueue::Forgot;
        } else {
            currentWord = Word();
            currentQueueType = CurrentQueue::None;
        }

        qDebug() << currentWord.word;

        displayCurrentWord();
    }
}
